package fsahoraires.gui.pages;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public abstract class EditPage extends AbstractPage {

	private Composite comp;
	private int labelWidth;

	public EditPage(String title, String image) {
		super(title, image);
	}

	protected Control createContent(Composite parent) {
		comp = new Composite(parent, SWT.NONE);
		labelWidth = 0;
		initFields();
		// layout
		FormLayout layout = new FormLayout();
		layout.marginBottom = 5;
		layout.marginLeft = 5;
		layout.marginRight = 5;
		layout.marginTop = 5;
		comp.setLayout(layout);
		Control[] children = comp.getChildren();
		for (int i = 0; i < children.length; i++) {
			FormData fd = new FormData();
			if (i % 2 == 0) {
				// label
				fd.top = (i == 0 ? new FormAttachment(0) : new FormAttachment(
						children[i - 1], 5));
				fd.right = new FormAttachment(0, labelWidth);
			} else {
				// contrôle
				fd.top = (i == 1 ? new FormAttachment(0) : new FormAttachment(
						children[i - 2], 5));
				fd.left = new FormAttachment(0, labelWidth);
				fd.right = new FormAttachment(100);
			}
			children[i].setLayoutData(fd);
		}
		return comp;
	}

	private void addLabel(String text) {
		final Label label = new Label(comp, SWT.RIGHT);
		label.setText(text.concat(" : "));
		label.pack();
		labelWidth = Math.max(labelWidth, label.getSize().x);
	}

	protected Composite addCompositeField(String label) {
		addLabel(label);
		return new Composite(comp, SWT.NONE);
	}

	protected Label addLabelField(String label, String text) {
		addLabel(label);
		final Label lbl = new Label(comp, SWT.LEFT);
		lbl.setText(text);
		return lbl;
	}

	protected Text addTextField(String label) {
		addLabel(label);
		return new Text(comp, SWT.BORDER);
	}

	protected abstract void initFields();

}
